package com.wmm;

public class ThreadTest implements Runnable{

    private int flag; //锁的控制符

    public ThreadTest(int flag) {
        this.flag = flag;
    }

    //静态锁对象
    static Object lock1 = new Object();
    static Object lock2 = new Object();


    @Override
    public void run() {
        System.out.println("当前的锁标志：" + flag);
        if (flag == 0) {
            synchronized (lock1) {
                try {
                    System.out.println("线程：" + Thread.currentThread().getName() + "已获得锁" + lock1);
                    Thread.sleep(500);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("线程：" + Thread.currentThread().getName() + "等待获得锁" + lock2);
                synchronized (lock2) {
                    System.out.println("线程：" + Thread.currentThread().getName() + "已获得锁" + lock2);
                }
            }
        }

        if (flag == 1) {

            synchronized (lock2) {
                try {
                    System.out.println("线程：" + Thread.currentThread().getName() + "已获得锁" + lock2);
                    Thread.sleep(500);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("线程：" + Thread.currentThread().getName() + "等待获得锁" + lock1);
                synchronized (lock1) {
                    System.out.println("线程：" + Thread.currentThread().getName() + "已获得锁" + lock1);
                }
            }
        }
    }


    public static void main(String[] args) {
        ThreadTest test1 = new ThreadTest(0);
        ThreadTest test2 = new ThreadTest(1);
        Thread thread1 = new Thread(test1);
        Thread thread2 = new Thread(test2);
        thread1.start();
        thread2.start();
    }


}
